package com.jdy.hotel.support;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import java.lang.reflect.Constructor;

public class BaseViewModelFactory implements ViewModelProvider.Factory {

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> aClass) {
        if (ViewModel.class.isAssignableFrom(aClass)) {
            try {
                Constructor<T> constructor = aClass.getDeclaredConstructor((Class<?>[]) null);
                constructor.setAccessible(true);//强制访问
                return constructor.newInstance();
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }
        } else {
            throw new IllegalArgumentException("Unknown ViewModel class");
        }
    }
}
